package com.qsl;

import com.alibaba.fastjson.JSON;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilerConfiguration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 青石路
 */
public class GroovyDemo {

    public static void main(String[] args) {
        CompilerConfiguration cfg = new CompilerConfiguration();
        cfg.setScriptBaseClass(FunctionScript.class.getName());
        GroovyShell shell = new ExpressionShell(cfg);
        shell.getClassLoader().clearCache();
        // 复合表达式
        Script script = shell.parse("isEqual(name1,name2)&&isEqual(hi,stringConcat(f,pyFuncExec(expr)))");
        PythonFuncModel model = new PythonFuncModel();
        // 小写转大写
        model.setScript("def greet_with_time(param):\n" +
                "    return param.upper()");
        // 返回类型，9：String
        model.setReturnType(9);
        // 函数参数
        List<PythonFuncModel.FuncParam> params = new ArrayList<>();
        params.add(new PythonFuncModel.FuncParam("param", 9, "cityName", 1));
        model.setParams(params);

        String exprJson = JSON.toJSONString(model);
        Map<String, String> map = new HashMap<>();
        map.put("name1", "zhangsan");
        map.put("name2", "张三");
        map.put("f", "hello,");
        map.put("hi", "hello,CHANGSHA");
        map.put("expr", exprJson);
        map.put("cityName", "changsha");
        Binding binding = new Binding(map);
        script.setBinding(binding);
        boolean exprResult = (Boolean) script.run();
        // exprResult = hello,CHANGSHA
        System.out.println(exprResult);
    }
}
